package org.example.xsda.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.xsda.common.PageResult;
import org.example.xsda.entity.*;
import org.example.xsda.exception.BusinessException;
import org.example.xsda.mapper.*;
import org.example.xsda.vo.StudentProfileVO;
import org.example.xsda.vo.StudentRecordVO;
import org.example.xsda.vo.StudentScoreExportVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 家长服务
 */
@Slf4j
@Service
public class ParentService {

    @Resource
    private ParentStudentMapper parentStudentMapper;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private ClassesMapper classesMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private StudentScoreMapper studentScoreMapper;

    @Resource
    private StudentRecordMapper studentRecordMapper;

    /**
     * 获取当前家长关联的所有学生（孩子）
     */
    public List<StudentProfileVO> getMyChildren() {
        // 1. 获取当前登录的家长用户ID
        Long parentUserId = StpUtil.getLoginIdAsLong();

        // 2. 查询家长关联的所有学生
        LambdaQueryWrapper<ParentStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ParentStudent::getParentId, parentUserId);
        List<ParentStudent> parentStudents = parentStudentMapper.selectList(wrapper);

        if (parentStudents == null || parentStudents.isEmpty()) {
            log.info("家长 {} 暂无关联的学生", parentUserId);
            return new ArrayList<>();
        }

        // 3. 查询学生详细信息
        List<StudentProfileVO> children = new ArrayList<>();
        for (ParentStudent ps : parentStudents) {
            Student student = studentMapper.selectById(ps.getStudentId());
            if (student == null) {
                continue;
            }

            // 构建学生档案VO
            StudentProfileVO vo = buildStudentProfile(student);
            children.add(vo);
        }

        log.info("家长 {} 查询关联学生成功，共 {} 人", parentUserId, children.size());
        return children;
    }

    /**
     * 获取指定学生的详细档案信息（需要验证家长权限）
     */
    public StudentProfileVO getChildDetail(Long studentId) {
        // 1. 验证当前家长是否有权限查看该学生
        Long parentUserId = StpUtil.getLoginIdAsLong();
        
        LambdaQueryWrapper<ParentStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ParentStudent::getParentId, parentUserId)
               .eq(ParentStudent::getStudentId, studentId);
        ParentStudent relation = parentStudentMapper.selectOne(wrapper);

        if (relation == null) {
            throw new BusinessException("您无权查看该学生信息");
        }

        // 2. 查询学生详细信息
        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            throw new BusinessException("学生信息不存在");
        }

        return buildStudentProfile(student);
    }

    /**
     * 构建学生档案VO
     */
    private StudentProfileVO buildStudentProfile(Student student) {
        StudentProfileVO vo = new StudentProfileVO();
        
        // 基本信息
        vo.setStudentId(student.getId());
        vo.setStudentNo(student.getStudentNo());
        vo.setUserId(student.getUserId());
        vo.setGender(student.getGender());
        vo.setGenderText(student.getGender() == 1 ? "男" : "女");
        vo.setBirthday(student.getBirthday());
        vo.setEnrollDate(student.getEnrollDate());
        vo.setAddress(student.getAddress());
        vo.setPhone(student.getPhone());
        vo.setIdPhoto(student.getIdPhoto());
        vo.setStatus(student.getStatus());
        vo.setStatusText(getStatusText(student.getStatus()));
        vo.setRemark(student.getRemark());

        // 计算年龄
        if (student.getBirthday() != null) {
            vo.setAge(Period.between(student.getBirthday(), LocalDate.now()).getYears());
        }

        // 计算入学年份
        if (student.getEnrollDate() != null) {
            vo.setEnrollYear(student.getEnrollDate().getYear());
        }

        // 查询用户信息（获取姓名和头像）
        if (student.getUserId() != null) {
            SysUser user = sysUserMapper.selectById(student.getUserId());
            if (user != null) {
                vo.setRealName(user.getRealName());
                vo.setAvatar(user.getAvatar());
                vo.setUsername(user.getUsername());
                vo.setAccountStatus(user.getStatus());
                
                // 角色信息
                vo.setRoleName("学生"); // 家长查看的都是学生档案，固定为"学生"
            }
        }

        // 查询院系信息
        if (student.getDeptId() != null) {
            Dept dept = deptMapper.selectById(student.getDeptId());
            if (dept != null) {
                vo.setDeptId(dept.getId());
                vo.setDeptName(dept.getDeptName());
            }
        }

        // 查询班级信息
        if (student.getClassId() != null) {
            Classes classes = classesMapper.selectById(student.getClassId());
            if (classes != null) {
                vo.setClassId(classes.getId());
                vo.setClassName(classes.getClassName());
                
                // 查询班主任信息
                if (classes.getHeadTeacherId() != null) {
                    SysUser headTeacher = sysUserMapper.selectById(classes.getHeadTeacherId());
                    if (headTeacher != null) {
                        vo.setHeadTeacherName(headTeacher.getRealName());
                    }
                }
            }
        }

        // TODO: 可以添加成绩统计信息（从 score 表查询）
        // vo.setAverageScore(calculateAverageScore(student.getId()));
        // vo.setTotalCredits(calculateTotalCredits(student.getId()));
        // vo.setCourseCount(calculateCourseCount(student.getId()));

        return vo;
    }

    /**
     * 获取学生成绩列表（只读，需验证权限）
     */
    public PageResult<StudentScore> getChildScores(Long studentId, Integer current, Integer size) {
        // 1. 验证家长权限
        verifyParentPermission(studentId);

        // 2. 分页查询成绩
        Page<StudentScore> page = new Page<>(current, size);
        LambdaQueryWrapper<StudentScore> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentScore::getStudentId, studentId)
               .orderByDesc(StudentScore::getCreateTime);
        
        Page<StudentScore> resultPage = studentScoreMapper.selectPage(page, wrapper);
        
        log.info("家长查询学生 {} 成绩，共 {} 条", studentId, resultPage.getTotal());
        
        return new PageResult<>(
                resultPage.getTotal(),
                resultPage.getRecords(),
                resultPage.getCurrent(),
                resultPage.getSize()
        );
    }

    /**
     * 获取学生档案记录列表（只读，需验证权限）
     */
    public PageResult<StudentRecordVO> getChildRecords(Long studentId, Integer current, Integer size) {
        // 1. 验证家长权限
        verifyParentPermission(studentId);

        // 2. 分页查询档案记录
        Page<StudentRecord> page = new Page<>(current, size);
        LambdaQueryWrapper<StudentRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentRecord::getStudentId, studentId)
               .orderByDesc(StudentRecord::getCreateTime);
        
        Page<StudentRecord> resultPage = studentRecordMapper.selectPage(page, wrapper);
        
        // 3. 转换为 VO
        List<StudentRecordVO> voList = resultPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        log.info("家长查询学生 {} 档案记录，共 {} 条", studentId, resultPage.getTotal());
        
        return new PageResult<>(
                resultPage.getTotal(),
                voList,
                resultPage.getCurrent(),
                resultPage.getSize()
        );
    }

    /**
     * 导出学生档案PDF（只读导出，需验证权限）
     * TODO: 需要实现家长专用的PDF生成逻辑
     */
    public void exportChildProfilePdf(Long studentId, HttpServletResponse response) {
        // 1. 验证家长权限
        verifyParentPermission(studentId);

        // 2. 暂时抛出提示，等待实现
        throw new BusinessException("PDF导出功能开发中，敬请期待");
        
        // TODO: 实现PDF导出
        // 可以参考 PdfService 的实现，为家长定制PDF内容
    }

    /**
     * 导出学生成绩Excel（只读导出，需验证权限）
     */
    public void exportChildScores(Long studentId, HttpServletResponse response) {
        // 1. 验证家长权限
        verifyParentPermission(studentId);

        // 2. 查询所有成绩
        LambdaQueryWrapper<StudentScore> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentScore::getStudentId, studentId)
               .orderByDesc(StudentScore::getCreateTime);
        List<StudentScore> scores = studentScoreMapper.selectList(wrapper);

        // 3. 转换为导出VO
        List<StudentScoreExportVO> exportList = scores.stream().map(score -> {
            StudentScoreExportVO vo = new StudentScoreExportVO();
            vo.setCourseName(score.getCourseName());
            vo.setScore(score.getScore());
            vo.setCredit(score.getCredit());
            vo.setSemester(score.getSemester());
            vo.setExamType("期末考试"); // 默认值，如果数据库有该字段可以从实体读取
            vo.setTeacherName("-"); // 默认值，如果需要可以关联查询教师表
            vo.setCreateTime(score.getCreateTime());
            vo.setRemark(""); // 默认值，如果数据库有该字段可以从实体读取
            return vo;
        }).collect(Collectors.toList());

        // 4. 使用 EasyExcel 导出
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = java.net.URLEncoder.encode("学生成绩_" + studentId, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            
            com.alibaba.excel.EasyExcel.write(response.getOutputStream(), StudentScoreExportVO.class)
                    .sheet("成绩列表")
                    .doWrite(exportList);
            
            log.info("家长导出学生 {} 成绩Excel成功，共 {} 条", studentId, exportList.size());
        } catch (Exception e) {
            log.error("导出成绩Excel失败", e);
            throw new BusinessException("导出失败：" + e.getMessage());
        }
    }

    /**
     * 导出学生档案记录Excel（只读导出，需验证权限）
     */
    public void exportChildRecords(Long studentId, HttpServletResponse response) {
        // 1. 验证家长权限
        verifyParentPermission(studentId);

        // 2. 查询所有档案记录
        LambdaQueryWrapper<StudentRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentRecord::getStudentId, studentId)
               .orderByDesc(StudentRecord::getCreateTime);
        List<StudentRecord> records = studentRecordMapper.selectList(wrapper);

        // 3. 转换为 VO 列表（包含更丰富的信息）
        List<StudentRecordVO> voList = records.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 4. 使用 EasyExcel 导出
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = java.net.URLEncoder.encode("学生档案记录_" + studentId, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            
            com.alibaba.excel.EasyExcel.write(response.getOutputStream(), StudentRecordVO.class)
                    .sheet("档案记录")
                    .doWrite(voList);
            
            log.info("家长导出学生 {} 档案记录Excel成功，共 {} 条", studentId, voList.size());
        } catch (Exception e) {
            log.error("导出档案记录Excel失败", e);
            throw new BusinessException("导出失败：" + e.getMessage());
        }
    }

    /**
     * 验证家长是否有权限查看该学生（私有方法）
     */
    private void verifyParentPermission(Long studentId) {
        Long parentUserId = StpUtil.getLoginIdAsLong();
        
        LambdaQueryWrapper<ParentStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ParentStudent::getParentId, parentUserId)
               .eq(ParentStudent::getStudentId, studentId);
        ParentStudent relation = parentStudentMapper.selectOne(wrapper);

        if (relation == null) {
            log.warn("家长 {} 尝试访问无权限的学生 {}", parentUserId, studentId);
            throw new BusinessException("您无权查看该学生信息");
        }
    }

    /**
     * 转换档案记录为 VO
     */
    private StudentRecordVO convertToVO(StudentRecord record) {
        StudentRecordVO vo = new StudentRecordVO();
        vo.setId(record.getId());
        vo.setStudentId(record.getStudentId());
        vo.setRecordType(record.getRecordType());
        vo.setRecordTypeName(getRecordTypeName(record.getRecordType()));
        vo.setContent(record.getContent());
        vo.setFileId(record.getFileId());
        vo.setCreateTime(record.getCreateTime());
        
        // 使用创建时间作为记录日期
        if (record.getCreateTime() != null) {
            vo.setRecordDate(record.getCreateTime().toLocalDate());
        }
        
        // 查询创建人姓名
        if (record.getCreateUser() != null) {
            SysUser creator = sysUserMapper.selectById(record.getCreateUser());
            if (creator != null) {
                vo.setCreatorName(creator.getRealName());
                vo.setCreateUser(creator.getId());
            }
        }
        
        return vo;
    }

    /**
     * 获取档案记录类型名称
     */
    private String getRecordTypeName(Integer recordType) {
        if (recordType == null) return "未知";
        switch (recordType) {
            case 1: return "奖惩记录";
            case 2: return "异动记录";
            default: return "其他";
        }
    }

    /**
     * 获取学生状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1: return "在籍";
            case 2: return "休学";
            case 3: return "毕业";
            case 4: return "退学";
            default: return "未知";
        }
    }
}

